﻿using KongMing.WebTools.Common;
using KongMing.WebTools.Models;
using System.Text;

namespace KongMing.WebTools.Service
{
    public class SqlBuilder
    {
        public OrmModel table;

        public StringBuilder str = new StringBuilder("");
        public SqlBuilder(OrmModel sqlTable)
        {
            table = sqlTable;
        }

        /// <summary>
        /// 构建sqlserver建表语句
        /// </summary>
        public string BuildSqlTable()
        {
            if (!string.IsNullOrWhiteSpace(table.TableRemark))
                str.AppendLine($"--{table.TableRemark}");
            str.AppendLine($"CREATE TABLE [{table.SqlTableName}]");
            str.AppendLine("(");
            bool hasPK = table.Fields.Any(x => x.IsPrimaryKey);
            for (int i = 0; i < table.Fields.Count; i++)
            {
                if (string.IsNullOrWhiteSpace(table.Fields[i].FieldName))
                    continue;
                str.AppendLine(BuildSqlField(table.Fields[i], (i == table.Fields.Count - 1) && !hasPK));
            }
            var keyFieldNames = table.Fields.Where(x => x.IsPrimaryKey).Select(x => x.SqlFieldName).ToList();
            if (keyFieldNames.Count > 0)
            {
                var pk_str = string.Join(',', keyFieldNames);
                str.AppendLine($"CONSTRAINT PK_{table.SqlTableName} PRIMARY KEY ([{pk_str}])");
            }
            str.AppendLine(");");
            str.AppendLine("GO");
            var result = str.ToString();
            return result;
        }


        /// <summary>
        /// 构建sqlserver表字段
        /// </summary>
        public string BuildSqlField(Field field, bool withNoFloat)
        {
            string str_dataType = Tools.FixSqlDataType(field.DataType, field.Length);
            string str_identity = field.IsIdentity ? " IDENTITY" : "";
            string str_isnull = field.IsNullable ? " NULL" : " NOT NULL";
            string str_default = field.SqlDefaultValue == null ? "" : $" DEFAULT ('{field.SqlDefaultValue}')";
            string str_remark = (withNoFloat ? "" : ",") + (string.IsNullOrWhiteSpace(field.Remark) ? "" : "--" + field.Remark);
            string _str = $"[{field.SqlFieldName}] {str_dataType}{str_isnull}{str_identity}{str_default}{str_remark} ";
            return _str;
        }
    }
}
